#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import re
import os 

#
def getRequireContent(path):
    start = 0
    end = 0

    requirecontent = ""
    currentline = 0
    commonFile = open(path, "r+")
    for (num, value) in enumerate(commonFile):
        # print ("line num is: ",num,"content:",value)
        if value.find("require") != -1:
            if start == 0:
                start = num+1
            requirecontent = requirecontent+value
            currentline = num+1
    end = currentline
    commonFile.close()

    return start-1, end

#
# 获取require 的起点终点行号
#


def getEndLine(path):
    end = 0

    currentline = 0
    commonFile = open(path, "r+")
    for (num, value) in enumerate(commonFile):
        currentline = num+1
    end = currentline
    commonFile.close()

    return end

#
# 获取某段字符串 特定子串出现次数
#


def word_count_in_str(string, keyword):
    return len(string.split(keyword))-1

#
# 获取function字段出现次数
#


def getFunctionCount(path):
    commonFile = open(path, "r+")
    content = commonFile.read()
    count = (word_count_in_str(content, 'function'))

    commonFile.close()
    return count

# 获取参数的起点终点（require 和第一个function的行号）


def getParamContent(path, index):
    functioncount = 0
    requirecontent = ""
    currentline = 0
    commonFile = open(
        path, "r+")

    for (num, value) in enumerate(commonFile, 0):
        # print ("line num is: ",num,"content:",value)
        if value.find("function") != -1:
            requirecontent = requirecontent+value
            currentline = num+1
            functioncount = functioncount+1
            if index == functioncount:
                break

    commonFile.close()
    return currentline-1


def loadDataSet(path, start, end):
    f = open(path, "r")
    content = ""
    for line in f.readlines()[start:end]:
        content = content+line
    return content
    f.close()

# 返回两个标签之间的内容


def key_match(path):
    symbol = "function"
    endsymbol = "end   "
    lines = 0
    with open(path, 'r') as f:
        buffser = f.read()
        # buffser = buffser.replace('\n', '')
        pattern = re.compile(symbol+'(.*?)'+endsymbol, re.S)
        result = pattern.findall(buffser)
        if result != []:
            # print(result)
            return str(result[0])
            #self.lines +=1
            # print("匹配到的行数：",self.lines)
        else:
            print("没有找到你输入的关键字")

# 切片法
def reverse1(content):
    s = content
    return s[::-1]

# 获取最后一行行号
def getEndSymbolLine(path, content, line):
    path=path.split("index.lua")[0]+"ss.lua"
    f=open(path,"w")
    
    content=reverse1(content)
    f.write(content)
    f.close()
    f=open(path,"r")
    pos=0
    for (num, value) in enumerate(f):
        if value.find("dne") != -1:     
            # print(num)
            pos=int(num)
            break
       
    f.close()        
    os.remove(path)
    return pos

